package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entiity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map param){
        //1、获取用户输入的手机号和验证码
        String telephone = (String)param.get("telephone");
        String validateCode =(String)param.get("validateCode");
        //2、验证验证码是否正确
        //2.1   从redis中获取缓存的验证码
        String validateCodeInServer = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if(validateCodeInServer!=null&&validateCode!=null&&validateCodeInServer.equals(validateCode)){
            //验证码正确
            //1、判断该手机号的用户是否是会员
            Member member = memberService.findByTelephone(telephone);
            if(member==null){
                //如果不是会员，则将其注册成会中
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }


            //将用户信息以手机号作为键，并将member转换成json，存储到redis中
            String s = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,1800,s);

            //将手机号通过cookie写到用户的电脑中
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);



           return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else{
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }



    }
}
